package org.budo.support.hex.converter;

/**
 * @author lmw
 */
public abstract class AbstractHexConverter implements HexConverter {
    private char[] baseChars;

    public char[] getBaseChars() {
        return baseChars;
    }

    public void setBaseChars(char[] baseChars) {
        this.baseChars = baseChars;
    }

    public long toBase10(String value) {
        char[] chars = new StringBuilder(value).reverse().toString().toCharArray();
        return this.toBase10(chars);
    }

    private long toBase10(char[] chars) {
        long n = 0;
        int pow = 0;
        for (char item : chars) {
            n += toBase10(this.getBaseChars()[item], pow);
            pow++;
        }
        return n;
    }

    private long toBase10(int n, int pow) {
        return n * (long) Math.pow(this.getBaseChars().length, pow);
    }

    public String fromBase10(long value) {
        if (value < 0) {
            throw new IllegalArgumentException("value can not less than 0, value=" + value);
        }

        if (value == 0) {
            return "0";
        }

        StringBuilder stringBuilder = new StringBuilder("");

        while (value > 0) {
            value = this.fromBase10(value, stringBuilder);
        }

        return stringBuilder.reverse().toString();
    }

    private long fromBase10(long i, final StringBuilder sb) {
        int rem = (int) (i % this.getBaseChars().length);
        sb.append(this.getBaseChars()[rem]);
        return i / this.getBaseChars().length;
    }
}